<template>
  <view class="container">
    <!-- 搜索栏 -->
    <uv-sticky bgColor="#fff">
      <view class="search-bar" @click="goSearch">
        <uni-icons type="search" size="18" color="#666" />
        <text class="placeholder">输入城市/区域/租金搜索房源</text>
      </view>
    </uv-sticky>

    <!-- 轮播图 -->
    <uv-swiper radius="0" class="swiper" :list="bannerList" height="250" interval="5000" indicator indicatorMode="line" circular />

    <!-- 分类导航 -->
    <view class="content">
      <view class="flex flex-row justify-between category-grid">
        <view class="category-item" v-for="(item, index) in categories" :key="index" @click="handleCategory(item)">
          <image class="icon" mode="widthFix" :src="`${item.src}`" />
          <view class="category-text">
            <text>{{ item.label }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 推荐房源 -->
    <view class="section-title">推荐房源</view>
    <view class="recommend-scroll">
      <view v-for="(item, index) in recommendList" :key="item.id" class="house-item"
        :style="{ backgroundColor: `${item.background}` }">
        <view class="info">
          <text class="title ellipsis">{{ item.title }}</text>
          <text class="desc ellipsis">{{ item.desc }}</text>
        </view>
        <view :class="[`theme_pack_${index}`, 'themepack-img']"></view>
      </view>
    </view>

    <!-- 分类列表 -->
    <uv-sticky bgColor="#fff" class="list-nav">
      <uv-tabs :list="tabs" @change="handleTabClick"></uv-tabs>
    </uv-sticky>
    <view class="list-scroll" :style="{ height: boxHeight }">
      <listCard v-if="active % 2 === 0" :dataList="dataList" :status="status" />
      <gridCard v-else :dataList="dataList" :status="status" />
      <uv-load-more :status="status" />
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue'
import { debounce } from 'lodash';
import { onReachBottom, onShow } from '@dcloudio/uni-app';
import { getHouseList } from '@/api/houseApi'
import type { IHouseItem, IRecommendItem, IHouseItemResponseData } from '@/types/house'
import listCard from '@/components/custom/listCard.vue';
import gridCard from '@/components/custom/gridCard.vue';


const bannerList = ref(['/static/banner/banner1.jpg', '/static/banner/banner2.jpg'])
const categories = ref([
  { label: '新房', src: '/static/img/icon1.png', path: '/pages/tenant/new-house' },
  { label: '二手房', src: '/static/img/icon2.png', path: '/pages/tenant/second-hand' },
  { label: '租房', src: '/static/img/icon3.png', path: '/pages/tenant/rental' },
  { label: '商铺', src: '/static/img/icon4.png', path: '/pages/tenant/commercial' },
  { label: '找小区', src: '/static/img/icon5.png', path: '/pages/tenant/apartment' }
])

const recommendList = ref<IRecommendItem[]>([
  {
    id: '1',
    title: '特价房专区',
    cover: '/static/img/house1.jpg',
    desc: '好而不贵 特价好房源',
    background: '#F1F6F7',
  },
  {
    id: '2',
    title: '楼盘热榜',
    cover: '/static/img/house1.jpg',
    desc: '人气户型榜',
    background: '#FBFAF2',
  },
  {
    id: '3',
    title: '稀缺江景',
    cover: '/static/img/house1.jpg',
    desc: '稀缺江景，可遇而不可求',
    background: '#FAF8F5',
  },
  {
    id: '4',
    title: '大型社区',
    cover: '/static/img/house1.jpg',
    desc: '大型社区通常会自带比较齐全的配套和完善的规划',
    background: '#F4F8F3',
  }
])
const page = ref(0)
const total = ref(10) // 假设总共有10条数据，这里可以根据实际情况进行设置
const active = ref(0)
const dataList = ref<IHouseItem[]>([])
const status = ref('loadmore')
const tabs = ref([{ name: '推荐' }, { name: '新房' }, { name: '二手房' }, { name: '租房' }, { name: '商铺' }, { name: '写字楼' }, { name: '装修' }])
const loading = ref(false)
const boxTop = ref(0)
const boxHeight = ref('auto')
let originalTop = 0;

onShow(() => {
  nextTick(() => {
    uni.createSelectorQuery().select(".list-nav").boundingClientRect(function (data) { //data - 各种参数
      if (Array.isArray(data)) {
        data = data[0];
      }
      originalTop = data?.top || 0;
    }).exec()
  })
})

const loadData = async () => {
  try {
    loading.value = true;
    status.value = 'loading';
    console.log(page.value)
    const res = await getHouseList(page.value, active.value) as IHouseItemResponseData;
    page.value++
    dataList.value = [...dataList.value, ...res.data]
    status.value = 'loadmore';
    nextTick(() => {
      boxHeight.value = 'auto'
    })
  } catch (err) {
    console.log(err)
    uni.showToast({ title: '数据加载失败', icon: 'none' })
  } finally {
    loading.value = false;
  }
}

const goSearch = () => {
  uni.navigateTo({ url: '/pages/tenant/search/index' })
}

const handleCategory = (item: any) => {
  uni.navigateTo({ url: item.path })
}

const handleTabClick = debounce((item) => {
  boxHeight.value = '2000rpx'
  boxTop.value = 0
  active.value = item.index
  page.value = 1
  dataList.value = []
  let scrollTop = 0;
  uni.createSelectorQuery().select(".list-scroll").boundingClientRect(function (data) { //data - 各种参数
    if (Array.isArray(data)) {
      data = data[0];
    }
    scrollTop = data?.top || 0;
  }).exec()
  if (scrollTop < 20) {
    uni.pageScrollTo({
      scrollTop: originalTop,
      duration: 10
    })
  }

  loadData()
}, 500, { 'leading': true, 'trailing': false })

onReachBottom(() => {
  if (loading.value) return;
  if (page.value >= total.value) { status.value = 'nomore'; return; }
  loadData();
});


loadData()
</script>


<style lang="scss" scoped>
.container {
  height: 100%;
}

.swiper {
  margin-top: 20rpx;
}

.search-bar {
  padding: 16rpx 30rpx;
  display: flex;
  align-items: center;
  border-radius: 18px;
  background: #f8f8f8;
  vertical-align: middle;

  .placeholder {
    font-size: 28rpx;
    color: #c0c6cc;
    margin-left: 10rpx;
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin: 40rpx 10px 20rpx;
  color: #333;
}

.recommend-scroll {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
  margin: 20rpx;

  .house-item {
    position: relative;
    flex: 1;
    width: calc(50% - 8rpx);

    .info {
      display: block;
      float: left;
      width: calc(100% - 12px);
      padding: 24px 0 20px 12px;
      position: relative;
      z-index: 1;

      .title {
        display: block;
        font-size: 16px;
        color: #1f2326;
        line-height: 16px;
        margin-right: 60px;
      }

      .desc {
        display: block;
        margin-top: 8px;
        font-size: 11px;
        color: #9aa0a6;
        margin-right: 60px;
        line-height: 12px;
      }
    }

    .themepack-img {
      position: absolute;
      right: 0;
      top: 0;
      display: block;
      background: url('~@/static/img/theme_pack_icons.png') no-repeat;
      background-size: 280px 160px;
      z-index: 0;
      width: 70px;
      height: 80px;
    }

    .theme_pack_0 {
      background-position: 0 0;
    }

    .theme_pack_1 {
      background-position: 0 -80px;
    }

    .theme_pack_2 {
      background-position: -70px 0;
    }

    .theme_pack_3 {
      background-position: -140px 0;
    }
  }

  .ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
.list-scroll {
  padding: 20rpx; 
}
.category-grid {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 30rpx 0;
  background: #fff;
}

.category-item {
  flex: 1;
  text-align: center;
  margin-right: 10rpx;
  font-size: 24rpx;
  color: $uni-text-color;

  &:last-child {
    margin-right: 0;
  }

  .icon {
    overflow: hidden;
    height: 120rpx;
    width: 120rpx;
  }
}

.category-text {
  color: #282828;
}

.reach-bottom {
  padding: 36rpx;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}
</style>
